package top.mcwebsite.playandroid.lib.markdown.render

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.ast.ASTNode
import top.mcwebsite.playandroid.lib.markdown.BlockVerticalPadding
import top.mcwebsite.playandroid.lib.markdown.utils.parseLink

data class MarkdownImage(
    val description: String,
    val link: String,
    var size: IntSize = IntSize(180, 180)
) : Inline

@Composable
fun ImageInlineContent(markdownImage: MarkdownImage, markdownState: MarkdownState, size: IntSize): InlineTextContent {
    return InlineTextContent(
        placeholder = Placeholder(width = size.width.sp, height = size.height.sp, PlaceholderVerticalAlign.Center),
        children = {
            Image(image = markdownImage) { imageSize ->
//                markdownImage.size = imageSize
            }
        }
    )
}


@Composable
fun Image(
    image: MarkdownImage,
    onLoadSuccess: (Size) -> Unit
) {
    Box(
        modifier = Modifier
            .padding(vertical = BlockVerticalPadding),
        contentAlignment = Alignment.Center
    ) {

        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data(image.link)
                .size(coil.size.Size.ORIGINAL)
                .build(),
            contentDescription = image.description, transform = { state ->
                if (state is AsyncImagePainter.State.Success) {
                    onLoadSuccess.invoke(state.painter.intrinsicSize)
                }
                state
            })
    }
}


fun parseImage(astNode: ASTNode, text: String): MarkdownImage {
    var imageDescription: String = ""
    var imageLink: String = ""
    astNode.children.forEach {
        when (it.type) {
            MarkdownElementTypes.INLINE_LINK -> {
                val link = parseLink(it, text)
                imageDescription = link.first
                imageLink = link.second
            }
        }
    }
    return MarkdownImage(imageDescription, imageLink)
}